package com.ysy.tz.core.utils;

import com.ysy.tz.core.annotation.ThrowableConsumer;
import com.ysy.tz.core.annotation.ThrowableFunction;
import com.ysy.tz.core.engine.ApplicationContext;
import java.util.function.Consumer;
import java.util.function.Function;
import org.apache.ibatis.session.SqlSession;

public class SQLUtils {

    public static <T, R> R executeSQLWithReturn(Class<T> cls, Function<T, R> function) {
        SqlSession sqlSession = null;

        R result;
        try {
            sqlSession = ApplicationContext.sqlSessionFactory.openSession(true);
            T t = sqlSession.getMapper(cls);
            result = function.apply(t);
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }

        }

        return result;
    }

    public static <T, R> R executeSQLWithReturnException(Class<T> cls, ThrowableFunction<T, R> function) throws Exception {
        SqlSession sqlSession = null;

        R var4;
        try {
            sqlSession = ApplicationContext.sqlSessionFactory.openSession(true);
            T t = sqlSession.getMapper(cls);
            var4 = function.apply(t);
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }

        }

        return var4;
    }

    public static <T> void executeSQL(Class<T> cls, Consumer<T> consumer) {
        SqlSession sqlSession = null;

        try {
            sqlSession = ApplicationContext.sqlSessionFactory.openSession(true);
            T t = sqlSession.getMapper(cls);
            consumer.accept(t);
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }

        }

    }

    public static <T> void executeSQLException(Class<T> cls, ThrowableConsumer<T> consumer) throws Exception {
        SqlSession sqlSession = null;

        try {
            sqlSession = ApplicationContext.sqlSessionFactory.openSession(true);
            T t = sqlSession.getMapper(cls);
            consumer.accept(t);
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }

        }

    }

    public static void executeSQLTransException(ThrowableConsumer<SqlSession> consumer) throws Exception {
        SqlSession sqlSession = null;

        try {
            sqlSession = ApplicationContext.sqlSessionFactory.openSession(false);
            consumer.accept(sqlSession);
            sqlSession.commit();
        } catch (RuntimeException var7) {
            sqlSession.rollback();
            throw var7;
        } finally {
            sqlSession.getConnection().setAutoCommit(true);
            if (sqlSession != null) {
                sqlSession.close();
            }

        }

    }
}
